package org.ajida.linux.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.ajida.common.LogUtil;
import org.ajida.common.StringUtil;

/**
 * linux下脚本执行工具，非远程
 * @author CaiDdongyu
 * @date 2022-3-5
 */
public class ShellUtil {
	public static String exec(String[] commands)throws Exception {
		InputStream inputStream = null;
		InputStream errorStream = null;
		PrintWriter out = null;
		StringBuilder buf = new StringBuilder();
		try {
			Process pop = Runtime.getRuntime().exec("/bin/bash");
	        // 获取其正常的输出流
			inputStream = pop.getInputStream();
	        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
	        BufferedReader br = new BufferedReader(inputStreamReader);
	        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(pop.getOutputStream())), true);
            for (String line : commands) {
                out.println(line);
            }
            out.println("exit");// 这个命令必须执行，否则in流不结束。
	        
	        String line = null;
	        buf.setLength(0);
	        while ((line = br.readLine()) != null) {
	        	LogUtil.log(line);
	        	buf.append(line).append("\r\n");
	        }

	        // 获取其错误的输出流
	        errorStream = pop.getErrorStream();
	        InputStreamReader errorStreamReader = new InputStreamReader(errorStream, "UTF-8");
	        BufferedReader errorBr = new BufferedReader(errorStreamReader);
	        String errorLine = null;
	        boolean hasError = false;
	        while ((errorLine = errorBr.readLine()) != null) {
	        	hasError = true;
	        	LogUtil.log(errorLine);
	        }
	        if(hasError){
	        	if(buf.indexOf("KB/s")<0){
	        		throw new Exception(buf.toString());
	        	}
	        }
		} catch (Exception e) {
			if(e.getMessage() != null && StringUtil.isNotEmpty(e.getMessage().trim())) {
				throw e;
			}
		} finally {
			if(inputStream != null){
				try {
					inputStream.close();
				} catch (Exception e2) {}
			}
			if(errorStream != null){
				try {
					errorStream.close();
				} catch (Exception e2) {}
			}
			if(out != null) {
				try {
					out.close();
				} catch (Exception e2) {}
			}
		}

//        pop.waitFor();
        return buf.toString();
    }

}
